<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="身份证号" prop="nationalId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.nationalId"-->
      <!--          placeholder="请输入身份证号"-->
      <!--          clearable-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="手机号" prop="phoneNumber">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.phoneNumber"-->
      <!--          placeholder="请输入手机号"-->
      <!--          clearable-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="所属系别" prop="department">
        <el-input
            v-model="queryParams.department"
            placeholder="请输入所属系别"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['teacher:teacher:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['teacher:teacher:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['teacher:teacher:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['teacher:teacher:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['teacher:teacher:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teacherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="70" align="center"/>
      <el-table-column label="序号" type="index" width="50px" align="center" prop="id"/>
      <el-table-column label="姓名" align="center" prop="name" show-overflow-tooltip/>
      <el-table-column label="工号" align="center" prop="employeeNumber" show-overflow-tooltip/>
      <el-table-column label="民族" align="center" prop="nationality">
        <template #default="scope">
          <dict-tag :options="nation_choose" :value="scope.row.nationality"/>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="身份证号" align="center" show-overflow-tooltip>-->
      <!--        <template v-slot="scope">-->
      <!--          {{ maskNumber(scope.row.nationalId, 3, 4) }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="手机号" align="center" show-overflow-tooltip>-->
      <!--        <template v-slot="scope">-->
      <!--          {{ maskNumber(scope.row.phoneNumber, 3, 4) }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column
          label="身份证号"
          align="center"
          show-overflow-tooltip
      >
        <template #default="scope">
          {{ desensitizeNationalId(scope.row.nationalId) }}
        </template>
      </el-table-column>
      <!-- 手机号 -->
      <!--      <el-table-column-->
      <!--          label="手机号"-->
      <!--          align="center"-->
      <!--          show-overflow-tooltip-->
      <!--      >-->
      <!--        <template #default="scope">-->
      <!--          {{ desensitizePhoneNumber(scope.row.phoneNumber) }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column
          label="年龄"
          align="center"
          show-overflow-tooltip
      >
        <template #default="scope">
          {{ calculateAgeFromIdCard(scope.row.nationalId) }}
        </template>
      </el-table-column>
      <el-table-column label="所属系别" align="center" prop="department" show-overflow-tooltip/>
      <el-table-column label="岗位" align="center" prop="position" show-overflow-tooltip/>
      <el-table-column label="职称" align="center" prop="title"/>
      <el-table-column label="职称获取时间" align="center" prop="titleAcquisitionDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.titleAcquisitionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="第一学历" align="center" prop="firstDegree"/>
      <el-table-column label="第一学历专业" align="center" width="120px" prop="firstDegreeObject"/>
      <el-table-column label="最高学历" align="center" prop="highestDegree">
        <template #default="scope">
          <el-button type="text" icon="el-icon-edit"
                     @click="$download.resource(scope.row.highestDegree)">{{ scope.row.highestDegree }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="最高学历专业" align="center" width="120px" prop="highestDegreeObject"/>
      <el-table-column label="就职状态" align="center" prop="employmentType">
        <template #default="scope">
          <dict-tag :options="teacher_first" :value="scope.row.employmentType"/>
        </template>
      </el-table-column>
      <el-table-column label="政治面貌" align="center" prop="politicalAffiliation">
        <template #default="scope">
          <dict-tag :options="teacher_status" :value="scope.row.politicalAffiliation"/>
        </template>
      </el-table-column>
      <el-table-column label="入职时间" align="center" prop="hireDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.hireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks"/>
      <el-table-column label="操作" align="center" width="150px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['teacher:teacher:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['teacher:teacher:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改教师信息对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="teacherRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工号" prop="employeeNumber">
              <el-input v-model="form.employeeNumber" placeholder="请输入工号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="民族" prop="nationality">
              <el-select v-model="form.nationality" placeholder="请选择民族">
                <el-option
                    v-for="dict in nation_choose"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别">
                <el-option
                    v-for="dict in sys_user_sex"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="nationalId">
              <el-input v-model="form.nationalId" placeholder="请输入身份证号"/>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="手机号" prop="phoneNumber">-->
          <!--              <el-input v-model="form.phoneNumber" placeholder="请输入手机号" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="所属系别" prop="department">
              <el-input v-model="form.department" placeholder="请输入所属系别"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="政治面貌" prop="politicalAffiliation">
              <el-select v-model="form.politicalAffiliation" placeholder="请选择政治面貌">
                <el-option
                    v-for="dict in teacher_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" prop="position">
              <el-input v-model="form.position" placeholder="请输入岗位"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职称" prop="title">
              <el-input v-model="form.title" placeholder="请输入职称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称获取时间" prop="titleAcquisitionDate">
              <el-date-picker v-model="form.titleAcquisitionDate" type="date" placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="第一学历" prop="firstDegree">
              <el-input v-model="form.firstDegree" placeholder="请输入第一学历"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第一学历专业" prop="firstDegreeObject">
              <el-input v-model="form.firstDegreeObject" placeholder="请输入第一学历专业"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="最高学历" prop="highestDegree">
          <file-upload v-model="form.highestDegree" type="textarea" />
          <br>
          <div
              class="upload-tip"
              style="font-size:12px;color: #FF5733;margin-top: 5px;">
            请上传大小不超过10MB，格式为PDF的文件。</div>

        </el-form-item>
        <el-form-item label="最高学历专业" prop="highestDegreeObject">
          <el-input v-model="form.highestDegreeObject" placeholder="请输入最高学历专业"/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="就职状态" prop="employmentType">
              <el-select v-model="form.employmentType" placeholder="请选择0专职1兼职">
                <el-option
                    v-for="dict in teacher_first"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职时间" prop="hireDate">
              <el-date-picker v-model="form.hireDate" type="date" placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport"/>
              是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                     @click="importTemplate">下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Teacher">
import {listTeacher, getTeacher, delTeacher, addTeacher, updateTeacher} from "@/api/teacher/teacher";
import {reactive} from "vue";
import {getToken} from "@/utils/auth.js";
import FileUpload from "@/components/FileUpload/index.vue";

const {proxy} = getCurrentInstance();
const {
  nation_choose,
  teacher_status,
  sys_user_sex,
  teacher_first
} = proxy.useDict('nation_choose', 'teacher_status', 'sys_user_sex', 'teacher_first');

const teacherList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    nationalId: null,
    phoneNumber: null,
    department: null,
  },
  rules: {
    name: [
      {required: true, message: "姓名不能为空", trigger: "blur"},
      {
        pattern: new RegExp('^[a-zA-Z\u4e00-\u9fa5]{2,7}$'),
        message: "姓名只能是2到7位的英文或汉字",
        trigger: "blur"
      }
    ],
    employeeNumber: [
      {required: true, message: "工号不能为空", trigger: "change"}
    ],
    nationality: [
      {required: true, message: "民族不能为空", trigger: "change"}
    ],
    gender: [
      {required: true, message: "性别不能为空", trigger: "change"}
    ],
    nationalId: [
      {required: true, message: "身份证号不能为空", trigger: "blur"},
      {
        pattern: new RegExp('^\\d{18}$'),
        message: "身份证号必须为18位数字",
        trigger: "blur"
      }
    ],
    // phoneNumber: [
    //   { required: true, message: "手机号不能为空", trigger: "blur" },
    //   {
    //     pattern: new RegExp('^\\d{11}$'),
    //     message: "手机号必须为11位数字",
    //     trigger: "blur"
    //   }
    // ],
    department: [ // 假设department是系别
      {
        pattern: new RegExp('^[\u4e00-\u9fa5]+$'),
        message: "系别只能是汉字",
        trigger: "blur"
      }
    ],
    position: [ // 假设position是岗位
      {
        pattern: new RegExp('^[\u4e00-\u9fa5]+$'),
        message: "岗位只能是汉字",
        trigger: "blur"
      }
    ],
    title: [ // 假设title是职称
      {
        pattern: new RegExp('^[\u4e00-\u9fa5]+$'),
        message: "职称只能是汉字",
        trigger: "blur"
      }
    ],
    firstDegree: [ // 假设firstEducation是第一学历
      {
        pattern: new RegExp('^[\u4e00-\u9fa5]+$'),
        message: "第一学历只能是汉字",
        trigger: "blur"
      }
    ],
    firstDegreeObject: [ // 假设firstMajor是第一学历专业
      {
        pattern: new RegExp('^[\u4e00-\u9fa5]+$'),
        message: "第一学历专业只能是汉字",
        trigger: "blur"
      }
    ],
    highestDegree: [ // 假设highestEducation是最高学历
      {
        pattern: new RegExp('^[\u4e00-\u9fa5]+$'),
        message: "最高学历只能是汉字",
        trigger: "blur"
      }
    ],
    highestDegreeObject: [ // 假设highestMajor是最高学历专业
      {
        pattern: new RegExp('^[\u4e00-\u9fa5]+$'),
        message: "最高学历专业只能是汉字",
        trigger: "blur"
      }
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

function maskNumber(number, startLength, endLength) {
  if (!number) return '';
  const start = number.slice(0, startLength);
  const end = number.slice(-endLength);
  const maskedPart = '*'.repeat(number.length - startLength - endLength);
  return `${start}${maskedPart}${end}`;
}

/** 进行身份证号的脱敏处理*/
function desensitizeNationalId(id) {
  if (!id) return '';
  return id.replace(/(\d{4})(\d{10})(\d{4})/, '$1********$3');
}

/** 进行手机号的脱敏处理*/
// function desensitizePhoneNumber(phone) {
//   if (!phone) return '';
//   return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
// }
/** 计算出生年龄 */
function calculateAgeFromIdCard(idCard) {
  // Assuming the idCard format is 'YYYYMMDD' for birthdate
  const birthYear = parseInt(idCard.substring(6, 10));
  const currentYear = new Date().getFullYear();
  return currentYear - birthYear;
}

/** 查询教师信息列表 */
function getList() {
  loading.value = true;
  listTeacher(queryParams.value).then(response => {
    teacherList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 上传文件相关 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/teacher/teacher/importData"
});

/**
 * 导入按钮操作
 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("teacher/teacher/importTemplate", {}, `teacher_template_${new Date().getTime()}.xlsx`);
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
  getList();
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    employeeNumber: null,
    nationality: null,
    gender: null,
    nationalId: null,
    phoneNumber: null,
    department: null,
    position: null,
    title: null,
    titleAcquisitionDate: null,
    firstDegree: null,
    firstDegreeObject: null,
    firstDegreeDate: null,
    highestDegree: null,
    highestDegreeObject: null,
    highestDegreeDate: null,
    employmentType: null,
    politicalAffiliation: null,
    hireDate: null,
    createName: null,
    createTime: null,
    updateName: null,
    updateTime: null,
    deleteFlag: null,
    departmentId: null,
    remarks: null
  };
  proxy.resetForm("teacherRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加教师信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTeacher(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改教师信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["teacherRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTeacher(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTeacher(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除教师信息编号为"' + _ids + '"的数据项？').then(function () {
    return delTeacher(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('teacher/teacher/export', {
    ...queryParams.value
  }, `teacher_${new Date().getTime()}.xlsx`)
}

getList();
</script>
